
package com.zhongketech.sunflower.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import com.zhongketech.sunflower.Constant;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.http.AndroidHttpClient;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.ImageButton;
import android.widget.ImageView;

//import com.fiship.cibn.threadPoolUtil.ThreadPool;
//import com.fiship.cibn.threadPoolUtil.task.LoadImageTask;

/**
 * 异步加载bitMap对象
 * 
 * @author chm
 * @version [版本号, 2013-3-9]
 * @since 
 */
@SuppressLint("HandlerLeak")
public class AsyncBitmapLoader {
    private static final String TAG = "AsyncBitmapLoader";

    /**
     * 内存图片软引用缓冲
     */
    private static HashMap<String, SoftReference<Bitmap>> imageCache = null;

    private static final String userAgent = "SAITION_USER_AGENT";

    public static File cacheDir = null;

    private static AsyncBitmapLoader mAsyncBitmapLoader = null;

    /**
     * 创建线程池对象
     */
    // private ExecutorService executorService =
    // Executors.newFixedThreadPool(5); // 固定五个线程来执行任务

    // public ThreadPool threadPool = new ThreadPool(10, 3);
    public final Handler handler = new Handler();

    private AsyncBitmapLoader() {
        imageCache = new HashMap<String, SoftReference<Bitmap>>();
        final String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            cacheDir = new File(Constant.ROOT_ADDR + "imgCache");
            // 检查/mnt/sdcard/saition文件夹是否存在，不存在则新建文件夹
            if (!cacheDir.exists() || !cacheDir.isDirectory()) {
                cacheDir.mkdirs();
            }
        }
    }

    public static AsyncBitmapLoader getInstance() {
        if (null == mAsyncBitmapLoader) {
            mAsyncBitmapLoader = new AsyncBitmapLoader();
        }
        return mAsyncBitmapLoader;
    }

    public String getFileFullName(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }
        int index = filePath.lastIndexOf("/");
        String bitmapName = filePath.substring(index + 1);
        String prefixName = filePath.substring(0, index);
        prefixName = prefixName.replace(".", "");
        prefixName = prefixName.replace("/", "");
        prefixName = prefixName.replace(":", "");
        String fullName = prefixName + bitmapName;
        return fullName;
    }

    public Bitmap loadBitmap(final ImageView imageView, final String imageURL,
            final ImageCallBack imageCallBack) {
        if (TextUtils.isEmpty(imageURL)) {
            if (null != imageView && null != imageCallBack) {
                imageCallBack.imageLoad(imageView, null);
            }
            return null;
        }
        // 在内存缓存中，则返回Bitmap对象
        if (imageCache.containsKey(imageURL)) {
            SoftReference<Bitmap> reference = imageCache.get(imageURL);
            Bitmap bitmap = reference.get();
            if (bitmap != null) {
                if (null != imageView && null != imageCallBack) {
                    imageCallBack.imageLoad(imageView, bitmap);
                }
                return bitmap;
            }
        }
        // 加上一个对本地缓存的查找
        if (null != cacheDir) {
            // 本地缓存存在
            String bitmapName = getFileFullName(imageURL);
            if (bitmapName == null) {
                return null;
            }
            File[] cacheFiles = cacheDir.listFiles();
            if (null != cacheFiles) {
                int i = 0;
                for (; i < cacheFiles.length; i++) {
                    if (bitmapName.equals(cacheFiles[i].getName())) {
                        break;
                    }
                }
                if (i < cacheFiles.length) {
                    Bitmap bitmap = BitmapFactory.decodeFile(cacheDir.getPath()
                            + "/" + bitmapName);
                    imageCache.put(imageURL, new SoftReference<Bitmap>(bitmap));
                    if (bitmap != null) {
                        if (null != imageView && null != imageCallBack) {
                            imageCallBack.imageLoad(imageView, bitmap);
                        }
                        return bitmap;
                    }
                }
            }
        }

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (null != imageView && null != imageCallBack) {
                    imageCallBack.imageLoad(imageView, (Bitmap) msg.obj);
                }
            }
        };

        // 如果不在内存缓存中，也不在本地（被jvm回收掉），则开启线程下载图片
        new Thread() {
            @Override
            public void run() {
                AndroidHttpClient client = AndroidHttpClient
                        .newInstance(userAgent);
                HttpGet request = new HttpGet(imageURL);
                Bitmap bitmap = null;
                // 发送GET请求，并将响应内容转换成字符串
                InputStream bitmapIs = null;
                try {
                    HttpResponse response = client.execute(request);
                    bitmapIs = new ByteArrayInputStream(
                            EntityUtils.toByteArray(response.getEntity()));
                    bitmap = BitmapFactory.decodeStream(bitmapIs);
                    bitmap = getSmallBitmap(bitmap);
                    imageCache.put(imageURL, new SoftReference<Bitmap>(bitmap));
                } catch (ClientProtocolException e1) {
                    ILog.d(TAG, "ClientProtocolException");
                } catch (Exception e1) {
                    ILog.d(TAG, "IOException");
                } finally {
                    try {
                        if (null != bitmapIs) {
                            bitmapIs.close();
                            bitmapIs = null;
                        }
                    } catch (IOException e) {
                        ILog.d(TAG, "IOException");
                    }

                    Message msg = handler.obtainMessage(0, bitmap);
                    handler.sendMessage(msg);

                    client.close();
                }
                // 把图片写入文件做缓存
                writeToFile(imageURL, bitmap);
            }

        }.start();
        return null;
    }

    public Bitmap imageButtonLoadBitmap(final ImageButton imageView,
            final String imageURL, final ImageButtonCallBack imageCallBack) {
        if (TextUtils.isEmpty(imageURL)) {
            if (null != imageView && null != imageCallBack) {
                imageCallBack.imageLoad(imageView, null);
            }
            return null;
        }
        // 在内存缓存中，则返回Bitmap对象
        if (imageCache.containsKey(imageURL)) {
            SoftReference<Bitmap> reference = imageCache.get(imageURL);
            Bitmap bitmap = reference.get();
            if (bitmap != null) {
                if (null != imageView && null != imageCallBack) {
                    imageCallBack.imageLoad(imageView, bitmap);
                }
                return bitmap;
            }
        }
        // 加上一个对本地缓存的查找
        if (null != cacheDir) { // 本地缓存存在
            String bitmapName = getFileFullName(imageURL);
            if (bitmapName == null) {
                return null;
            }
            File[] cacheFiles = cacheDir.listFiles();
            if (null != cacheFiles) {
                int i = 0;
                for (; i < cacheFiles.length; i++) {
                    if (bitmapName.equals(cacheFiles[i].getName())) {
                        break;
                    }
                }
                if (i < cacheFiles.length) {
                    Bitmap bitmap = BitmapFactory.decodeFile(cacheDir.getPath()
                            + "/" + bitmapName);
                    imageCache.put(imageURL, new SoftReference<Bitmap>(bitmap));
                    if (bitmap != null) {
                        if (null != imageView && null != imageCallBack) {
                            imageCallBack.imageLoad(imageView, bitmap);
                        }
                        return bitmap;
                    }
                }
            }
        }

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (null != imageView && null != imageCallBack) {
                    imageCallBack.imageLoad(imageView, (Bitmap) msg.obj);
                }
            }
        };

        // 如果不在内存缓存中，也不在本地（被jvm回收掉），则开启线程下载图片
        new Thread() {
            @Override
            public void run() {
                AndroidHttpClient client = AndroidHttpClient
                        .newInstance(userAgent);
                HttpGet request = new HttpGet(imageURL);
                Bitmap bitmap = null;
                // 发送GET请求，并将响应内容转换成字符串
                InputStream bitmapIs = null;
                try {
                    HttpResponse response = client.execute(request);
                    bitmapIs = new ByteArrayInputStream(
                            EntityUtils.toByteArray(response.getEntity()));
                    bitmap = BitmapFactory.decodeStream(bitmapIs);
                    bitmap = getSmallBitmap(bitmap);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    System.out.println("==============>>>"
                            + baos.toByteArray().length / 1024);
                    imageCache.put(imageURL, new SoftReference<Bitmap>(bitmap));
                } catch (ClientProtocolException e1) {
                    ILog.d(TAG, "ClientProtocolException");
                } catch (Exception e1) {
                    ILog.d(TAG, "IOException");
                } finally {
                    try {
                        if (null != bitmapIs) {
                            bitmapIs.close();
                            bitmapIs = null;
                        }
                    } catch (IOException e) {
                        ILog.d(TAG, "IOException");
                    }

                    Message msg = handler.obtainMessage(0, bitmap);
                    handler.sendMessage(msg);

                    client.close();
                }
                // 把图片写入文件做缓存
                writeToFile(imageURL, bitmap);
            }
        }.start();
        return null;
    }

    /**
     * 缩放bitMap
     * 
     * @param bm
     * @return [参数说明]
     * @return Bitmap [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     */
    public Bitmap getSmallBitmap(Bitmap bm) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 设置想要的大小
        int newWidth = 80;
        int newHeight = 80;
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
    }

    public String writeToFile(final String imageURL, Bitmap bitmap) {
        if (null == cacheDir || null == bitmap) {
        	ILog.e(TAG, "writeToFile failed cacheDir:"+cacheDir+" bitmap:"+bitmap);
            return null;
        }
        String bitmapName = getFileFullName(imageURL);
        if (bitmapName == null) {
        	ILog.e(TAG, "writeToFile failed bitmapName:"+bitmapName);
            return null; 
        }
        String newBitmapUrl = cacheDir.getPath() + "/" + bitmapName;
        ILog.i(TAG, "writeToFile newBitmapUrl:"+newBitmapUrl);
        File bitmapFile = new File(newBitmapUrl);
        if (!bitmapFile.exists()) {
            try {
                bitmapFile.createNewFile();
            } catch (IOException e) {
            	ILog.e(TAG, "writeToFile failed bitmapFile:"+bitmapFile+" e:"+e);
            }
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(bitmapFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
            return newBitmapUrl;
        } catch (FileNotFoundException e) {
            ILog.d(TAG, "ClientProtocolException");
            return null;
        } catch (IOException e) {
            ILog.d(TAG, "ClientProtocolException");
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fos) {
                    fos.close();
                    fos = null;
                }
            } catch (IOException e) {
                ILog.d(TAG, "IOException");
            }
        }
        
		return newBitmapUrl;
    }

    /**
     * 回调接口
     */
    public interface ImageCallBack {
        public void imageLoad(ImageView imageView, Bitmap bitmap);
    }

    /**
     * 回调接口
     */
    public interface ImageButtonCallBack {
        public void imageLoad(ImageButton imageView, Bitmap bitmap);
    }

    public void releaseCache() {
        // 删除本地缓存的海报图片
        if (null != cacheDir && cacheDir.exists() && cacheDir.isDirectory()) {
            for (File imageFile : cacheDir.listFiles()) {
                imageFile.delete();
            }
        }

        final HashMap<String, SoftReference<Bitmap>> cache = imageCache;
        if (cache != null) {
            Collection<SoftReference<Bitmap>> values = cache.values();
            if (values == null) {
                return;
            }
            Iterator<SoftReference<Bitmap>> iter = values.iterator();
            while (iter.hasNext()) {
                SoftReference<Bitmap> r = iter.next();
                Bitmap b = r.get();
                if (b != null && !b.isRecycled()) {
                    b.recycle();
                }
            }
            cache.clear();
        }
    }

    public static Bitmap getSmallBitmapForVodList(Bitmap bm) {
        // 获得图片的宽高

        int width = bm.getWidth();

        int height = bm.getHeight();

        // 设置想要的大小

        int newWidth = 80;

        int newHeight = 80;

        // 计算缩放比例

        float scaleWidth = ((float) newWidth) / width;

        float scaleHeight = ((float) newHeight) / height;

        // 取得想要缩放的matrix参数

        Matrix matrix = new Matrix();

        matrix.postScale(scaleWidth, scaleHeight);

        // 得到新的图片

        return Bitmap.createBitmap(bm, 0, 0, width, height, matrix,

        true);
    }

//    public void loadImage(String imageUrl, ImageButton mPoster,
//            ImageButtonCallBack imageCallBack) {
//        // LoadImageTask loadImageTask = new LoadImageTask(imageUrl, mPoster,
//        // imageCallBack);
//        // if (!threadPool.addTaskToPool(loadImageTask))
//        // {
//        // ILog.e(AsyncBitmapLoader.class.toString(), "线程池中任务已满!");
//        // }
//    }
}
